# -*- coding: utf-8 -*-




from django.contrib.auth.models import User
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse,JsonResponse
from forms import LoginForm,UpdateProfileForm,UpdateEmailForm,AddCategoryForm,AddTagForm,AddArticleForm
from django.shortcuts import render,redirect,reverse
from django.core.cache import cache
from cmsauth.models import CmsUser
from qiniu import Auth,put_file
import qiniu.config
from django.views.decorators.http import require_http_methods
from django.core import mail
import hashlib
import time
from article.models import ArticleModel,CategoryModel,TagModel
from utils import myjson
from email.mime.text import MIMEText

# createsuperuser
# 登录函数
def cms_login(request):
	if request.method == 'GET':
		return render(request,'cms_login.html')
	else:
		print request.POST,'-'*10
		form = LoginForm(request.POST)
		if form.is_valid():
			username = form.cleaned_data.get('username',None)
			password = form.cleaned_data.get('password',None)
			remember = form.cleaned_data.get('remember',None)
			# 1. 先用authenticate进行验证
			user = authenticate(username=username,password=password)
			if user:
				# 2. 需要登录,
				# 3. 我们的login视图函数不要和login重名
				login(request,user)
				# 判断如果有remember,那么说明需要记住,使用None将
				# 使用settings.py中SESSION_COOKIE_AGE指定的值,
				# 这个值默认是14天
				if remember:
					request.session.set_expiry(None)
				else:
					# 浏览器一旦关闭,session就会过期
					request.session.set_expiry(0)
				nexturl = request.GET.get('next')
				if nexturl:
					return redirect(nexturl)
				else:
					return redirect(reverse('cms_index'))
			else:
				return render(request,'cms_login.html',{'error':u'用户名或密码错误!'})
		else:
			return render(request,'cms_login.html',{'error':form.get_error()})

# 登出函数
def cms_logout(request):
	logout(request)
	return redirect(reverse('cms_login'))

@login_required
def index(request):
	return render(request,'cms_index.html')

def settings(request):
	# 1. 可以修改用户名
	# 2. 可以修改头像
	# 3. 可以修改邮箱
	return render(request,'cms_settings.html')

@login_required
@require_http_methods(['POST'])
def update_profile(request):
	"""
		更新用户信息
		1. 更新头像(avatar)
		2. 更新用户名(username)
	"""
	form = UpdateProfileForm(request.POST)
	if form.is_valid():
		print request.POST
		avatar = form.cleaned_data.get('avatar',None)
		username = form.cleaned_data.get('username',None)
		# user = request.user
		user = User.objects.all().first() # 中间件设置当前的user到request上
		user.username = username
		user.save()
		# 1.如果CmsUser这个表里已经有数据和user对应了,就直接更新
		cmsuser = CmsUser.objects.filter(user__pk=user.pk).first()
		if not cmsuser:
			# 2.如果CmsUser这个表里没有数据和user对应,就应该新建,然后保存进去
			cmsuser = CmsUser(avatar=avatar,user=user)
		else:
			cmsuser.avatar = avatar
		cmsuser.save()
		return myjson.json_result()
	else:
		return myjson.json_params_error(message=form.errors.as_json())

# @login_required
@require_http_methods(['GET'])
def get_token(request):
	"""
	1. 客户端在上传图片到七牛之前,需要先从业务服务器
	上获取token,本函数就是获取token的函数
	2. 客户端获取到token后,拿到token后把token和图片一起上传到七牛服务器
	3. 七牛收到token和图片后,会判断当前token是否有效,如果有效,则会
	返回图片名到客户端和业务服务器.
	"""
	# 1. 先要设置AccessKey和SecretKey
	access_key = "gQ_GJcNspKLvzPa2PJfEM1_bppeBWpSRFIe5-Hjs"
	secret_key = "uva9lOwDFwNHpSXqkSb0aN_KZhFhWlIXNDTurSil"
	# 2. 授权
	q = Auth(access_key,secret_key)
	# 3. 设置七牛空间
	bucket_name = 'huadong'
	# 4. 生成token
	token = q.upload_token(bucket_name)
	# 5. 返回token,key必须为uptoken
	# return JsonResponse({'uptoken':token})
	# return myjson.json_result(data={'uptoken':token})
	return myjson.json_result(kwargs={'uptoken':token})

@login_required
@require_http_methods(['GET','POST'])
def update_email(request):
	if request.method == 'GET':
		return render(request,'cms_email.html')
	else:
		form = UpdateEmailForm(request.POST)
		if form.is_valid():
			email = form.cleaned_data.get('email',None)
			if email:
				# key=random,value=email
				# 发送链接到email这个邮箱,用户点击了才算认证通过
				# 1. 把用户的邮箱信息存储到缓存中
				code = hashlib.md5(str(time.time())+email).hexdigest()
				cache.set(code,email,600)
				check_url = request.scheme + '://' + request.get_host() + reverse('cms_check_email',kwargs={'code':code})
				# 2. 发送邮件到email这个邮箱
				subject = u'邮箱修改验证'
				# message中应该包含验证的链接
				message = u'博客验证链接,点击 ' +u'< a href="'+ check_url + u'" > check_code</a>'+u'  ,请在10分钟内完成注册。工作人员不会向您索取验证码，请勿泄露。消息来自：xx的博客'
				message = MIMEText(message, 'html', 'utf-8')
				from_mail = '27331032@qq.com'
				recipient_list = [email]
				mail.send_mail(subject,message,from_mail,recipient_list)
				return HttpResponse('success')
		else:
			return render(request,'cms_email.html',{'error':form.errors})

@login_required
@require_http_methods(['GET'])
def check_email(request,code):
	"""
		验证邮箱的url
	"""
	# 需要知道用户之前修改邮箱的时候填的是什么邮箱
	if len(code) > 0:
		# 通过code,在缓存里获取email
		email = cache.get(code)
		print email
		if email:
			user = request.user
			user.email = email
			# update_fileds这个参数可以指定需要保存哪些字段
			# 好处在于不需要保存没有更新的字段,提升效率
			user.save(update_fields=['email'])
			return HttpResponse(u'邮箱修改成功')
		else:
			return HttpResponse(u'该链接已经失效')
	else:
		return HttpResponse(u'该链接已经失效')

# 文章相关操作
# @login_required
def add_article(request):
	if request.method == 'GET':
		categorys = CategoryModel.objects.all()
		tags = TagModel.objects.all()
		data = {
			'categorys':categorys,
			'tags': tags
		}
		return render(request,'cms_addarticle.html',data)
	else:
		form = AddArticleForm(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			category = form.cleaned_data.get('category')
			desc = form.cleaned_data.get('desc')
			thumbnail = form.cleaned_data.get('thumbnail')
			content_html = form.cleaned_data.get('content_html')
			tags = request.POST.getlist('tags')
			user = request.user

			categoryModel = CategoryModel.objects.filter(pk=category).first()

			articleModel = ArticleModel(title=title,desc=desc,thumbnail=thumbnail,content_html=content_html,author=user,category=categoryModel)
			articleModel.save()
			#添加tags的多对多

			if tags:
				for tag in tags:
					tagModel = TagModel.objects.filter(pk=tag).first()
					if tagModel:
						articleModel.tags.add(tagModel)

			return myjson.json_result(data={})

		else:
			return myjson.json_params_error(message=form.errors.as_json())
		

@login_required
@require_http_methods(['POST'])
def add_category(request):
	form = AddCategoryForm(request.POST)
	if form.is_valid():
		categoryname = form.cleaned_data.get('categoryname',None)
		resultCategory = CategoryModel.objects.filter(name=categoryname).first()
		if not resultCategory:
			categoryModel = CategoryModel(name=categoryname)
			categoryModel.save()
			return myjson.json_result(data={'id':categoryModel.id,'name':categoryModel.name})
		else:
			# return JsonResponse({'error':u'不能設置同名的分類!','code':403})
			return myjson.json_params_error(message=u'不能設置同名的分類!')
	else:
		# return JsonResponse({'error':form.errors.as_json,'code':'403'});
		return myjson.json_params_error(message=u'表单验证失败')

# @login_required
@require_http_methods(['POST'])
def add_tag(request):
	form = AddTagForm(request.POST)
	if form.is_valid():
		tagname = form.cleaned_data.get('tagname')
		# 先判断一下数据库中是否已经存在同名的标签
		resultTag = TagModel.objects.filter(name=tagname).first()
		if not resultTag:
			# 如果没有,说明可以添加
			tagModel = TagModel(name=tagname)
			tagModel.save()
			return myjson.json_result(data={'id':tagModel.id,'name':tagModel.name})
		else:
			return myjson.json_params_error(message=u'不能设置同名标签!')
	else:
		return myjson.json_params_error(message=form.errors.as_json())


def test(request):
	# categoryModel = CategoryModel.objects.all().first()
	# data = {'id':categoryModel.id,'name':categoryModel.name}
	# return myjson.json_result(data=data)
	# dict1 = {'a':'aa','b':'bb'}
	# dict2 = {'1':'11','2':'22'}
	# result = dict(dict1,**dict2)
	# return HttpResponse(result)
	# 两个数组合并
	dict1 = {'username':'xt'}
	dict2 = {'password':'123456'}
	result = dict(dict1,**dict2)
	return myjson.json_result(data=result)
